package com.feizhou.oauth.service;

import java.util.List;

import com.feizhou.oauth.bean.UserBean;
import com.feizhou.oauth.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 * @version 1.0
 **/
@Service
public class SpringDataUserDetailsService implements UserDetailsService {
    
    @Autowired
    UserDao userDao;
    
    // 根据账号查询用户信息,
    // 通过@Service将SpringDataUserDetailsService注入容器，通过UserDetailsService接口表明该类的类型是UserDetailsService
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        
        // 将来连接数据库根据账号查询用户信息
        UserBean bean = userDao.getUserByUsername(username);
        if (bean == null) {
            // 如果用户查不到，返回null，由provider来抛出异常
            return null;
        }
        
        // 查询当前数据库的用户资源权限
        List<String> authorize = userDao.getAuthorize(bean.getId());
        String[] authorizeArr = new String[authorize.size()];
        authorize.toArray(authorizeArr);
        
        // 添加权限
        UserDetails userDetails = User.withUsername(bean.getUserName()).password(bean.getPassword())
                .authorities(authorizeArr).build();
        return userDetails;
    }
}
